<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.grade" placeholder="全部年级" clearable style="width: 120px" class="filter-item" size="mini" round @change="handleFilter">
        <el-option v-for="item in gradeoption" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input v-model="listQuery.name" placeholder="请输入关键字" style="width: 200px;margin-left: 10px" class="filter-item" size="mini" round @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" size="mini" style="margin-left: 10px" round @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" size="mini" style="margin-left: 10px;float:right" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" size="mini" style="margin-left: 10px;float:right" @click.prevent="delData">
        删除
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="77" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.className }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年级" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.classGrade }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地块" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.classFields }}</span>
        </template>
      </el-table-column>
      <el-table-column label="视频监控" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.classMonitor }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" size="medium" title="编辑" @click="handleUpdate(row)"><i class="el-icon-edit" />
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete(row)"><i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.className" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="temp.classGrade" placeholder="请选择年级" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in gradeoption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地块" prop="classFields">
          <el-select v-model="temp.classFields" multiple placeholder="请选择地块" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in fieldoption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="视频监控" prop="video">
          <el-select v-model="temp.classMonitor" multiple placeholder="请选择视频" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in videooption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="传感器" prop="sensor">
          <el-select v-model="temp.classSensor" multiple placeholder="请选择传感器" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in sensoroption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="作物" prop="crop">
          <el-select v-model="temp.classCrop" multiple placeholder="请选择作物" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in cropoption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="水肥机" prop="shuifeiji">
          <el-checkbox-group v-model="checkedwater" @change="handlechange">
            <el-checkbox v-for="item in Wateroption" :key="item.value" :label="item.label">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getClassList, addClassList, getcrop, deleteclassList, deleteclassLists, updateclassList } from '@/api/classManagement'
import { getall } from '@/api/grade'
import { getsensorList } from '@/api/sensor'
import { GetmonitorList } from '@/api/monitor'
import { getWater, getmutualList } from '@/api/mutual'
import { getPage } from '@/api/Field'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      checkedwater: [],
      sels: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        grade: ''
      },
      gradeoption: [],
      fieldoption: [],
      videooption: [],
      sensoroption: [],
      Wateroption: [],
      cropoption: [],
      temp: {
        item: [],
        // num:'',
        className: '',
        classGrade: '',
        classFields: [],
        classMonitor: [],
        classCrop: [],
        classId: '',
        classSensor: [],
        classWaterFertilizerMachine: [],
        fieldName: '',
        keyword: '',
        sensorName: '',
        baseName: '',
        regionName: '',
        remoteControlDeviceName: ''
        // classWaterFertilizerMachine:'',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        // className: [{ required: true, message: 'className is required', trigger: 'blur' }],
        // classGrade: [{ required: true, message: 'classGrade is required', trigger: 'blur' }],
        // classFields: [{ required: true, message: 'classFields is required', trigger: 'blur' }],
        // classMonitor: [{ required: true, message: 'classMonitor is required', trigger: 'blur' }],
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    getall().then(res => {
      // console.log(res.data)
      for (let i = 0; i < res.data.length; i++) {
        this.gradeoption.push({ value: `${res.data[i]}`, label: `${res.data[i]}` })
      }
    })
    GetmonitorList(this.temp).then(res => {
      // console.log(res)
      for (let i = 0; i < res.data.length; i++) {
        this.videooption.push({ value: `${res.data[i].videoMonitorDeviceName}`, label: `${res.data[i].videoMonitorDeviceName}` })
      }
    })
    getsensorList(this.temp).then(res => {
      for (let i = 0; i < res.data.records.length; i++) {
        this.sensoroption.push({ value: `${res.data.records[i].sensorName}`, label: `${res.data.records[i].sensorName}` })
      }
    })
    getmutualList(this.temp).then(res => {
      console.log(res)
      for (let i = 0; i < res.data.records.length; i++) {
        this.temp.baseName = res.data.records[i].baseName
        getWater(this.temp).then(res => {
          console.log(res)
          this.Wateroption.push({ value: `${res.data}`, label: `${res.data}` })
        })
        this.temp.baseName = ''
      }
    })
    getPage(this.temp).then(res => {
      // console.log(res)
      for (let i = 0; i < res.data.records.length; i++) {
        this.fieldoption.push({ value: `${res.data.records[i].fieldName}`, label: `${res.data.records[i].fieldName}` })
      }
    })
    getcrop().then(res => {
      for (let i = 0; i < res.data.records.length; i++) {
        this.cropoption.push({ value: `${res.data.records[i].cropName}`, label: `${res.data.records[i].cropName}` })
      }
    })
  },
  methods: {
    handlechange(value) {
      this.temp.classWaterFertilizerMachine = value
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    selectRow(sels) {
      this.sels = sels
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        for (let i = 0; i < this.sels.length; i++) {
          this.temp.item[i] = this.sels[i].classId
        }
        deleteclassLists(this.temp)
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        // this.getList()
      })
    },
    getList() {
      this.listLoading = true

      getClassList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        item: [],
        // num:'',
        className: '',
        classGrade: '',
        classFields: [],
        classMonitor: [],
        classCrop: '',
        classId: '',
        classSensor: '',
        classWaterFertilizerMachine: [],
        fieldName: '',
        keyword: '',
        sensorName: '',
        baseName: '',
        regionName: '',
        remoteControlDeviceName: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          addClassList(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateclassList(tempData).then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      console.log(row)
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteclassList(row)
        this.getList()
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    }
  }
}
</script>
